﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using NotifyPilot.WCF.Helpers;
using Yammer.api;

namespace NotifyPilot.WCF.NotifyClients
{
    public class YammerNotifyClient : NotifyClient, INotifyClient
    {
        private readonly YammerConfigParameters _config;
        private YammerClient _myYammer;

        protected YammerClient MyYammerClient
        {
            get
            {
                return this._myYammer ??
                       (this._myYammer = new YammerClient(this._config.ConsumerKey, this._config.ConsumerSecret,
                           this._config.BackUrl, this._config.Code, this._config.Token));
            }
        }

        public YammerNotifyClient(String xmlEvent, String tfsRootUrl)
            : base(xmlEvent, tfsRootUrl)
        {
            this._config = YammerConfigParametersFactory.LoadParameters();
        }

        public void Post()
        {
            try
            {

                if (ContentObject != null && this._config.HaveRequiredParameters &&
                    this._config.IsProballyReadyToPost)
                {
                    var message = String.Format("[{0} {1}] ", this.ContentObject.WorkItemType,
                        this.ContentObject.ID) + this.ContentObject.Descriptions;

                    var topics = new List<String> { this._config.DefaultTopic, this.ContentObject.ProjectName, 
                       this.ContentObject.Iteration };

                    var result = this.MyYammerClient.PostMessage(message, this._config.PublishGroup,
                                                    topics, new OpenGraphInMessage
                                                    {
                                                        og_url = this.ContentObject.Url,
                                                        og_title = this.ContentObject.Name,
                                                        og_fetch = true
                                                    });

                    var messageResult = result.meta.current_user_id + " | Messages:";
                    messageResult = result.messages.Aggregate(messageResult, (current, m) => current + ("[" + m.id + "/" + m.body.plain + "]"));

                    EventLog.WriteEntry(Helpers.Helpers.NotifyLogSource,
                        "YammerNotifier : " + messageResult, EventLogEntryType.Information);
                }
                else
                {
                    EventLog.WriteEntry(Helpers.Helpers.NotifyLogSource,
                        "Yammer : no token", EventLogEntryType.Warning);
                }
            }
            catch (Exception ex)
            {
                EventLog.WriteEntry(Helpers.Helpers.NotifyLogSource,
                    "YammerNotifier : " + ex.Message + "|" + ex.StackTrace, EventLogEntryType.Error);
            }
        }
    }
}